import { Injectable } from '@nestjs/common';
import { DistributionRate_Create_Dto } from './assets/distributionRate.dto';
import { InjectRepository } from '@nestjs/typeorm';
import { DistributionRate } from './assets/distributionRate.entity';
import { Repository } from 'typeorm';
import { DistributionRate_FindByUserClientId_Dto } from './assets/distributionRate.dto';
import { util_Db_Add } from '@/common/util/db';
import { Platform } from '../platform/assets/platform.entity';
import { Product } from '../product/assets/product.entity';
import { UserClient } from '../userClient/assets/userClient.entity';
import { Constant_Enum_Enum_UserClient_Type } from '@/common/constants/enum';
import { IRequest } from '@/common/typeScripts';

@Injectable()
export class DistributionRate_Service {
  constructor(
    @InjectRepository(DistributionRate)
    private distributionRate_Repository: Repository<DistributionRate>,
    @InjectRepository(Platform)
    private platform_Repository: Repository<Platform>,
    @InjectRepository(Product)
    private product_Repository: Repository<Product>,
    @InjectRepository(UserClient)
    private userClient_Repository: Repository<UserClient>,
  ) {}

  async distributionRate_Create(body: DistributionRate_Create_Dto) {
    const distributionRates = [];
    body.rates.map((item) => {
      item.products.map((itemed) => {
        const obj: any = {
          platform: this.platform_Repository.create({ id: item.platformId }),
          product: this.product_Repository.create({ id: itemed.productId }),
          firstOrderRate: itemed.firstOrderRate,
          secondOrderRate: itemed.secondOrderRate,
        };
        if (itemed.userClientId)
          obj.userClient = this.userClient_Repository.create({ id: itemed.userClientId });
        if (itemed.id) obj.id = itemed.id;
        distributionRates.push(obj);
      });
    });
    return await util_Db_Add({
      createDto: distributionRates,
      repository: this.distributionRate_Repository,
    });
  }

  async distributionRateWeb_My(req: IRequest) {
    const userClient = await this.userClient_Repository
      .createQueryBuilder('userClient')
      .where('userClient.id=:id', { id: req.user.userId })
      .getOne();
    const qb = this.distributionRate_Repository
      .createQueryBuilder('distributionRate')
      .leftJoin('distributionRate.product', 'product')
      .leftJoin('distributionRate.platform', 'platform')
      .select([
        'platform.id AS platformId',
        `JSON_ARRAYAGG(
          JSON_OBJECT("id",distributionRate.id,"productId", product.id, "firstOrderRate", distributionRate.firstOrderRate, "secondOrderRate", distributionRate.secondOrderRate)
        ) AS products`,
      ])
      .groupBy('platform.id');
    if (userClient.distributionType == Constant_Enum_Enum_UserClient_Type.UserClient_Type_Lock) {
      qb.where('distributionRate.userClientId = :userClientId', {
        userClientId: req.user.userId,
      });
    } else {
      qb.where('distributionRate.userClientId IS NULL');
    }
    return await qb.getRawMany();
  }

  async distributionRate_FindByUserClientId(query: DistributionRate_FindByUserClientId_Dto) {
    const qb = this.distributionRate_Repository
      .createQueryBuilder('distributionRate')
      .leftJoin('distributionRate.product', 'product')
      .leftJoin('distributionRate.platform', 'platform')
      .select([
        'platform.id AS platformId',
        `JSON_ARRAYAGG(
          JSON_OBJECT("id",distributionRate.id,"productId", product.id, "firstOrderRate", distributionRate.firstOrderRate, "secondOrderRate", distributionRate.secondOrderRate)
        ) AS products`,
      ])
      .groupBy('platform.id');
    if (query.userClientId) {
      qb.where('distributionRate.userClientId = :userClientId', {
        userClientId: query.userClientId,
      });
    } else {
      qb.where('distributionRate.userClientId IS NULL');
    }
    return await qb.getRawMany();
  }

  async distributionRate_FindOneById(id: number) {
    return await this.distributionRate_Repository
      .createQueryBuilder('distributionRate')
      .andWhere(`distributionRate.id = :id`, { id: id })
      .getOne();
  }
}
